package com.google.jguery.client.query;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.google.jguery.client.analyzer.Analyzer;
import com.google.jguery.client.analyzer.StandardAnalyzer;
import com.google.jguery.client.common.FieldText;

public class And extends CompoundQuery {

	public And() {	
	}
	
	public And(String term) {
		this(term, "body", new StandardAnalyzer());
	}
	
	public And(String term, Analyzer analyzer) {
		this(term, "body", analyzer);
	}
	
	public And(String text, String fieldName, Analyzer analyzer) {
		String [] words = analyzer.parse(text);
		for (String word : words) {
			subQueries.add(new Term(fieldName, word));
		}
	}

	public void setQueries(String text, Analyzer analyzer) {
		subQueries.clear();
		String [] words = analyzer.parse(text);
		for (String word : words) {
			subQueries.add(new Term(word));
		}
	}
	
	@Override
	public int estimateSize(Searcher searcher) {
		int size = Integer.MAX_VALUE;
		for (Query q : subQueries) {
			int s = q.estimateSize(searcher);
			if (s < size) size = s;
		}
		return size;
	}

	@Override
	public Set<FieldText> getAllTerms() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<Integer, Integer> getDocScoreMap(Searcher searcher) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public Set<Integer> getDocIds(Searcher searcher) {
		if (subQueries == null || subQueries.size() == 0) return null;
		int [] counter = new int[searcher.getDocCountAll()];
		for (Query subQuery : subQueries) {
			Set<Integer> docIds = subQuery.getDocIds(searcher);
			if (docIds == null || docIds.size() == 0) {
				return null;
			}
			for (int id : docIds) {
				counter[id] += 1;
			}
		}
		int targetHits = subQueries.size();
		Set<Integer> docIds = new HashSet<Integer>();
		for (int i=0; i<counter.length; i++) {
			if (counter[i] == targetHits) {
				docIds.add(i);
			}
		}
		return docIds;
	}
	
	public String toString() {
		if (subQueries == null || subQueries.size() == 0) return null;
		StringBuilder sb = new StringBuilder();
		sb.append("And(");
		for (Query subQuery: subQueries) {
			sb.append(subQuery + ",");
		}
		sb.append(")");
		return sb.toString();
	}

}
